package com.ccys.common.interceptor;

import com.ccys.common.constants.ContextConstants;
import com.ccys.common.enums.CodeEnum;
import com.ccys.common.util.JedisUtil;
import com.ccys.common.util.Kit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;


/**
 * 拦截器
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor{



    @Override
    public void afterCompletion(HttpServletRequest arg0,
                                HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {

    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
                           Object arg2, ModelAndView arg3) throws Exception {

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();

        String contentType = request.getHeader("content-type");
        String token = request.getHeader("token");
        String method = request.getMethod();

        if(!uri.contains(ContextConstants.APPLICATION_NAME+"/error")){
            log.info("=============请求路径：" + uri + "============");
            log.info("=============请求方式：" + method + "============");
            log.info("=============请求时间：" + DateFormat.getDateTimeInstance().format(new Date()) + "============");
            log.info("=============token："+(StringUtils.isBlank(token)?"无token":token)+"============");
            if (!(StringUtils.isNotBlank(contentType)&&contentType.contains("application/json"))) {
                log.info("=============请求参数:" + getParamString(request.getParameterMap()) + "=============");
            }
            log.trace(handler.toString());
        }else{
            response.setStatus(404);
            return true;
        }

        String reqMethod = request.getMethod();
        if ("OPTIONS".equals(reqMethod)) {
            response.setStatus(200);
            return false;
        }

        String[] urlArr = uri.split("/");

        StringBuffer sb = new StringBuffer("/");
        for (int i = 2; i < urlArr.length; i++) {
            sb.append(urlArr[i]).append("/");
        }

        //静态资源放行 后台页面sys  上传文件uploadFile
        if(uri.contains("/uploadFile/")){
            return true;
        }

        /**
         * 判断是否通过gateway校验
         */
        String pass = request.getHeader("gatewayPass");
        if(StringUtils.isBlank(pass)||!"ok".equals(pass)){
            response.setStatus(CodeEnum.ILLEGAL.codeOf());
            return false;
        }

        return true;
    }

    @SuppressWarnings("all")
    private String getParamString(Map<String, String[]> map) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String[]> e : map.entrySet()) {
            sb.append(e.getKey()).append("=");
            String[] value = e.getValue();
            if (value != null && value.length == 1) {
                sb.append(value[0]).append("\t");
            } else {
                sb.append(Arrays.toString(value)).append("\t");
            }
        }
        return sb.toString();
    }

}
